﻿var iwPortal = {
  preferences: [],
  themes: ['teal', 'steelblue', 'indigo', 'olivedrab', 'maroon', 'gray', 't09', 't11'],
  isPersonalizable: true,

  init: function(defaultWidgets, isPersonalizable) {
    if(preferences.widgets == null) {
      preferences.widgets = defaultWidgets;
    }
    iwPortal.isPersonalizable = isPersonalizable;
    iwPortal.activateWidgets();
    iwPortal.activateListsControls();
    iwPortal.makeSortable();
  },

  activateWidgets: function() {
    $('.widget', $('.widget-zone')).each(function () {
      $(this).mouseenter(function() {
        iwPortal.addWidgetControls($(this));
        $('.widget-head a.collapse, .widget-head a.settings, .widget-head a.remove', $(this)).show();
      }).mouseleave(function() {
        $('.widget-head a.collapse, .widget-head a.settings, .widget-head a.remove', $(this)).hide();
      });
    });
  },

  addWidgetControls: function (widget) {
    if(!widget.hasClass('widget')) return true;
    if(!widget.hasClass('no-collapse') && ($('.widget-head a.collapse', widget).length == 0)) {
      var zIndex = widget.parent().index();
      var wIndex = widget.parent().children().index(widget);

      var collapsed = (preferences.widgets[zIndex][wIndex].settings != undefined) && preferences.widgets[zIndex][wIndex].settings['collapsed'];
      $('<a href="#" class="collapse">&nbsp;</a>').addClass(collapsed ? 'expand' : '').click(function (e) {
        e.stopPropagation();

        $(this).toggleClass('expand')
          .parents('.widget')
          .find('.widget-content, .widget-footer').toggle();

        // update preferences
        if(!preferences.widgets[zIndex][wIndex].settings) {
          preferences.widgets[zIndex][wIndex].settings = new Object;
        }

        preferences.widgets[zIndex][wIndex].settings['collapsed'] = !$('.widget-content', $(this).parent().parent().parent()).is(':visible');
        iwPortal.savePreferences();
        return false;
      }).prependTo($('.collapse-wpr', widget));
    }
    
    if(!iwPortal.isPersonalizable) return false;
    if(!widget.hasClass('no-remove') && ($('.widget-head a.remove', widget).length == 0)) {
      $('<a href="#" class="remove"></a>').mousedown(function (e) {
        e.stopPropagation();
      }).click(function () {
        $(this).parents('.widget').animate( {
          opacity: 0
        }, function () {
          $(this).wrap('<div/>').parent().slideUp(function () {
            var zIndex = $(this).parent().index();
            var wIndex = $(this).parent().children().index($(this));
            $(this).remove();
            $('#widgets-catalog #' + preferences.widgets[zIndex][wIndex].wdid).attr('checked', false);

            // update preferences
            preferences.widgets[zIndex].splice(wIndex, 1);
            iwPortal.savePreferences();
          });
         });
        return false;
      }).appendTo($('.controls-wpr', widget));
    }

    if(!widget.hasClass('no-edit') && ($('.widget-head a.settings', widget).length == 0)) {
      $('<a href="#" class="settings"></a>').mousedown(function (e) {
        e.stopPropagation();
      }).toggle(function () {
        $(this).parents('.widget')
          .find('.edit-box').show().find('input').focus();
          return false;
        },function () {
          $(this).parents('.widget')
            .find('.edit-box').hide();
          return false;
        }).appendTo($('.controls-wpr', widget));
        $('<div class="edit-box" style="display:none; background-color:#cfcfcf;"/>').append((function() {
          var colorList = '<table style="margin:0;"><tr><td style="padding:5px; vertical-align:middle;">اللون:</td><td style="padding:8px 5px;"><ul class="colors" style="margin:0 20px 0 60px; ">';
          $(iwPortal.themes).each(function () {
            colorList += '<li class="color-' + this + '" style="width:15px; height:15px;" />';
          });
          return colorList + '</ul></td></tr></table>';
        })())
        .insertAfter($('.widget-head', widget));

      $('.edit-box ul.colors li', widget).click(function () {
        var colorStylePattern = /\bcolor-[\w]{1,}\b/,
        thisWidgetColorClass = $(this).parents('.widget').attr('class').match(colorStylePattern);
        if (thisWidgetColorClass) {
          var widget = $(this).parents('.widget');
          var newColorClass = $(this).attr('class').match(colorStylePattern)[0];
          widget.removeClass(thisWidgetColorClass[0]).addClass(newColorClass);

          var zIndex = widget.parent().index();
          var wIndex = widget.parent().children().index(widget);

          // update preferences
          if(!preferences.widgets[zIndex][wIndex].settings) {
            preferences.widgets[zIndex][wIndex].settings = new Object;
          }
          preferences.widgets[zIndex][wIndex].settings['color'] = newColorClass.substr(6);
          iwPortal.savePreferences();
        }
        return false;
      });
    }
  },

  activateListsControls: function() {
    $(document).on('click', '.widget-footer .show-more', function(e) {
      e.preventDefault();
      var widget = $(this).closest('li.widget');
      $('.widget-content li', widget).each(function() {
        if(!$(this).is(":visible")) {
          $(this).toggle();

          // update preferences
          var zIndex = widget.parent().index();
          var wIndex = widget.parent().children().index(widget);
          if(!preferences.widgets[zIndex][wIndex].settings) {
            preferences.widgets[zIndex][wIndex].settings = new Object;
          }
          preferences.widgets[zIndex][wIndex].settings['items_count'] = $('.widget-content li:visible', widget).length;
          iwPortal.savePreferences();
          return false;
        }
      });
    });

    $.fn.reverse = [].reverse;
    $(document).on('click', '.widget-footer .show-less', function(e) {
      e.preventDefault();
      var widget = $(this).closest('li.widget');
      if($('.widget-content li:visible', widget).length <= 3) return false;
      $.each($('.widget-content li', widget).reverse(), function() {
        if($(this).is(":visible")) {
          $(this).toggle();

          // update preferences
          var zIndex = widget.parent().index();
          var wIndex = widget.parent().children().index(widget);
          if(!preferences.widgets[zIndex][wIndex].settings) {
            preferences.widgets[zIndex][wIndex].settings = new Object;
          }
          preferences.widgets[zIndex][wIndex].settings['items_count'] = $('.widget-content li:visible', widget).length;
          iwPortal.savePreferences();
          return false;
        }
      });
    });
  },

  makeSortable: function() {
    if(!iwPortal.isPersonalizable) return;
    $sortableItems = $('> li', '.widget-zone');

    $sortableItems.find('.widget-head').css({
      cursor: 'move'
    }).mousedown(function (e) {
      $sortableItems.css({width:''});
      $(this).parent().css({
        width: $(this).parent().width() + 'px'
      });
    }).mouseup(function () {
      if(!$(this).parent().hasClass('dragging')) {
        $(this).parent().css({width:''});
      } else {
        $('.widget-zone').sortable('disable');
      }
    });

    var srcZone, srcWidget, dstZone, dstWidget;
    $('.widget-zone').sortable({
      items: $sortableItems,
      connectWith: $('.widget-zone'),
      handle: '.widget-head',
      placeholder: 'widget-placeholder',
      forcePlaceholderSize: true,
      revert: 300,
      delay: 100,
      opacity: 0.8,
      containment: 'document',
      start: function (e, ui) {
        $(ui.helper).addClass('dragging');
        srcZone = $(ui.item).parent().index();
        srcWidget = $(ui.item).parent().children().index(ui.item);
      },
      stop: function (e, ui) {
        $(ui.item).css({'top':0, 'left': 0});
        $(ui.item).css({width:''});
        $(ui.item).removeClass('dragging');
        $(ui.item).removeClass('hover');
        $('.widget-zone').sortable('enable');
        dstZone = $(ui.item).parent().index();
        dstWidget = $(ui.item).parent().children().index(ui.item);

        // update preferences
        preferences.widgets[dstZone].splice(dstWidget, 0, preferences.widgets[srcZone].splice(srcWidget, 1)[0]);
        iwPortal.savePreferences();
      }
    });

    $('.widget-head').mouseenter(function() {
      $(this).parent().parent().addClass('hover');
    }).mouseleave(function() {
      $(this).parent().parent().removeClass('hover');
    });
  },

  loadFeeds: function(feeds) {
    if(typeof google == 'undefined') {
      $.getScript('https://www.google.com/jsapi?key=ABQIAAAAsvBJDbGeRE60QF2iF-4texSPCZIFx7LUg--jk4cgHI5oFTPUZRSaXzxec-SIawOBSDBm0ZHV67TLYQ', function() {
        if(typeof google != 'object') {
          var widget = container.parent().parent().parent();
          $('.widget-content', widget).html('<div style="text-align:center"><img src="http://static.islamway.net/images/warning.gif" alt="" /><div dir="ltr" style="margin:5px;">Error</div></div>');
          return;
        }
        google.load('feeds', '1', {
          nocss: 1,
          callback: function() {
            iwPortal._loadFeeds(feeds);
          }
        });
      });
    } else {
      iwPortal._loadFeeds(feeds);
    }
  },
  
  _loadFeeds: function(feeds) {
    for (var i = 0; i < feeds.length; i++) {
      iwPortal._loadFeed(feeds[i].url, container = feeds[i].container);
    }
  },
  
  _loadFeed: function(url, container) {
    var feed = new google.feeds.Feed(url);
    feed.setNumEntries(7);
    feed.load(function(result) {
      if (result.error) {
        alert(result.error.message);
      } else {
        var widget = container.parent().parent().parent();
        $('h3', widget).text(result.feed.title);
        $('.widget-footer table td:nth-child(3)', widget).html('<a class="more" target="_blank" href="' + result.feed.link + ' ">المزيد</a>');
        $('li', container).remove();

        var zIndex = widget.parent().index();
        var wIndex = widget.parent().children().index(widget);
        var visible_items = (typeof preferences.widgets[zIndex][wIndex].settings['items_count'] == "undefined") ? 5 : preferences.widgets[zIndex][wIndex].settings['items_count'];

        for (var n = 0; n < result.feed.entries.length; n++) {
          var entry = result.feed.entries[n];
          $(container).append('<li' + ((n >= visible_items)? ' style="display:none;"' : '') + '><a target="_blank" href="' + entry.link + '" title="' + entry.contentSnippet + '">' + entry.title + '</a></li>');
        }
      }
    });
  },

  addFeedReader: function(url, zone) {
    var wpr = $('<div>').addClass('widget-wpr');
    wpr.append('<div class="widget-head clearfix"><div class="collapse-wpr"></div><h3 unselectable="on">...</h3><div class="controls-wpr"></div></div>');
    wpr.append('<div class="widget-content"><ul class="simple-list"></ul></div>');
    wpr.append('<div class="widget-footer"><table><tr><td width="1%"><a href="#" class="show-more" style="margin-right:3px;"></a></td><td width="1%"><a href="#" class="show-less"></a></td><td width="98%"></td></tr></table></div>');
    var widget = $('<li>').addClass('widget color-teal').append(wpr);
    zone.append(widget);

    $(window).scrollTop(widget.offset().top);
    iwPortal.loadFeeds([{ 'container': $('.widget-content ul', widget), 'url': url }]);

    // update preferences
    iwPortal.addWidget('feed-reader', {'url': url}, {});
    iwPortal.addWidgetControls(widget);
    iwPortal.makeSortable();
    widget.show();
  },

  addWidget: function(wdid, params, settings) {
    preferences.widgets[1][preferences.widgets[1].length] = {'wdid':wdid, 'params':params, 'settings':settings};
    iwPortal.savePreferences();
  },

  loadPreferences: function() {
    // Read preferences from cookie:
    if(document.cookie.length > 0) {
      var start = document.cookie.indexOf("preferences=");
      if(start != -1) {
        start = start + 12;
        end = document.cookie.indexOf(";", start);
        if(end == -1) end = document.cookie.length;
        preferences = JSON.parse((decodeURIComponent(document.cookie.substring(start, end))));
      }
    }
  },

  savePreferences: function() {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 30);
    document.cookie = 'preferences=' + encodeURIComponent(JSON.stringify(preferences)) + ";path=/;expires=" + exdate.toGMTString();
  },

  setPref: function(name, value) {
    preferences[name] = value;
    iwPortal.savePreferences();
  },

  getPref: function(name, defaultValue) {
    return (name in preferences) ? preferences[name] : defaultValue;
  }
};

/******************************************************************************/
var Playlist = {
  init: function() {
    var items = iwPortal.getPref('playlist');

    $('#playlist-items').sortable();

    $('#addto-playlist').click(function(e) {
      e.preventDefault();
      var resourceId = $(this).parent().data('resource');
      if(!isNaN(resourceId)) {
        Playlist.add(resourceId);
      }
    });

    $('#playlist-ctrl').click(function(e) {
      e.preventDefault();
      $('.userbar-dialog:not(#playlist)').hide();
      $('#playlist').toggle();
      if(!$('#playlist').is(':visible')) $('#playlist-items-wpr').hide();

      if(!$('#playlist object').length) {
        $.ajax({async: false, cache: true, url: '/flowplayer/flowplayer-3.2.8.min.js', dataType: 'script'});
        $.ajax({async: false, cache: true, url: '/flowplayer/flowplayer.playlist-3.2.8.min.js', dataType: 'script'});

        $f('playlist-player', {src: '/flowplayer/flowplayer-3.2.9.swf', wmode: 'transparent'}, {
          plugins: {
            controls: {
              url: '/flowplayer/flowplayer.controls-3.2.9.swf',
              fullscreen: false,
              playlist: false,
              width: 750,
              height: 37,
              autoHide: false,
              backgroundColor: 'transparent',
              backgroundGradient: 'none',
              timeColor: '#ff0000',
              timeSeparator: '/',
              durationColor: '#000000',
              progressColor: '#840204',
              bufferColor: '#a88081',
              sliderColor: '#b7b7b7',
              sliderBorder: 'none',
              buttonColor: '#494d53',
              buttonOverColor: '#171b21',
              volumeColor: '#5b5b5b',
              scrubberHeightRatio: 0.3,
              volumeSliderHeightRatio: 0.3
            }
          },
          clip: {
            autoPlay: false
          }
        });

        $f('playlist-player').playlist('#playlist-items', {
          loop:true,
          playingClass: 'playing',
          pausedClass: 'paused'
        });
      }
    });

    $('#playlist-items-ctrl').click(function(e) {
      e.preventDefault();
      $('#playlist-items-wpr').toggle();

      if($('#playlist-items-wpr').is(':visible')) {
        var viewer = $('#playlist-items-wpr');
        var vH = viewer.height();
        var vT = viewer.offset().top;
        var sTop = viewer.find(':first').height() - vH;
        $('#playlist-items-wpr').mousemove(function(e) {
          $(this).scrollTop(Math.round(sTop * (e.pageY - vT) / vH));
        });
      }
    });

    var play = function(direction) {
      var items = $('#playlist-items');
      var count = items.children().length;
      var index = items.children().index($('.playing', items)) + direction;
      if(index < 0) index = count - 1;
      if(index >= count) index = 0;
      $(items.children()[index]).click();
    }

    $('#playlist-prev').click(function(e) {
      e.preventDefault();
      play(-1);
    });

    $('#playlist-next').click(function(e) {
      e.preventDefault();
      play(+1);
    });

    $('#playlist-close').click(function(e) {
      e.preventDefault();
      $('#playlist-items-wpr').hide();
      $('#playlist').hide();
    });

    $('.playlist-remove').click(Playlist.removeEventHandler);
    $('#playlist-items').on('click', '.playlist-remove', Playlist.removeEventHandler);
  },

  add: function(resourceId) {
    $.getJSON('/resource/' + resourceId, function(resource) {
      scholar_name = '';
      for(var key in resource.Entry.Scholars[0].Translation) {
        scholar_name = resource.Entry.Scholars[0].Translation[key].name;
        break;
      }
      var items = iwPortal.getPref('playlist') ? iwPortal.getPref('playlist') : new Array();
      if($.inArray(resourceId, items) >= 0) return;
      items.push(resourceId);
      iwPortal.setPref('playlist', items);
      $('#playlist-items').append(
          '<a href="' + resource.url + '" data-resource="' + resource.id + '" class="clearfix">'
        + '<span class="playlist-item-info">'
        + '<span class="playlist-item-title">' + resource.Entry.title + '</span><span>' + ((resource.Entry.Scholars.length > 0) ? scholar_name : '') + '</span></span>'
        + '<span class="playlist-item-ctrls"><img class="playlist-move" src="http://static.islamway.net/images/playlist-move.png" alt="Move" /><img class="playlist-remove" src="http://static.islamway.net/images/playlist-remove.png" alt="Remove" />'
        + '</span></a>'
      );
      Playlist.updateCounter();
    });
  },

  remove: function(resourceId) {
    if(!iwPortal.getPref('playlist')) return;
    var items = iwPortal.getPref('playlist');
    var index = $.inArray(resourceId, items);
    if(index < 0) return;
    items.splice(index, 1);
    iwPortal.setPref('playlist', items);
    $('#playlist-items a[data-resource=\'' + resourceId + '\']').remove();
    Playlist.updateCounter();
  },
  
  removeEventHandler: function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).parent().parent().slideUp('slow', function() {
      Playlist.remove($(this).data('resource'));
    });
  },

  updateCounter: function() {
    $('#playlist-counter').text(parseInt($('#playlist-items a').length));
    $('#playlist-counter').parent().effect('highlight', {color: '#777'}, 500);
  }
};

/******************************************************************************/
function initSharingScripts() {
  $('#send-to-friend').click(function(e) {
    e.preventDefault();
    var sendToFriendDialog = $('<div></div>')
    .load(
      $('#send-to-friend').attr('href'),
      function() {
        ajaxifyFormSubmit('#send-to-friend-form');
        var urlParts = document.location.href.split('/');
        $('#SendToFriend_entry_id', sendToFriendDialog).val(parseInt(urlParts.pop()));
        $('#SendToFriend_entry_type', sendToFriendDialog).val(urlParts.pop());
      }
    )
    .dialog( {
      autoOpen: false,
      modal: true,
      width:500,
      title: $('#send-to-friend').data('tip')
    });

    var left = ($(window).width() - 500) / 2;
    sendToFriendDialog.dialog('option', 'position', [left, 70]).dialog('open');
  });

  $('#share a').click(function(e) {
    e.preventDefault();
    if($('#share-dlg').is(':visible')) {
      $('#share-dlg').hide();
    } else {
      $('#share-dlg').load($('#share a').attr('href'), function() {
        $('#sharing-widget a').click(function(e) {
          e.preventDefault();
          var titleRegExp = /\[TITLE\]/g;
          var urlRegExp = /\[URL\]/g;
          var url = this.href.replace(titleRegExp, document.title).replace(urlRegExp, document.location.href);
          window.open(url, '_sharingWindow', 'width=800,height=500,left=0,top=0,screenX=0,screenY=100');
          $('#share-dlg').hide();
        });
      }).show();
    }
  });

  window.fbAsyncInit = function() {
    FB.init({appId: '123429164410828', status: true, cookie: true, xfbml: true});
    FB.XFBML.parse();

    FB.Event.subscribe('edge.create', function(targetUrl){
      _gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
    });
  };

  (function() {
    var e = document.createElement('script');
    e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());

  (function() {
    var po = document.createElement('script');po.type = 'text/javascript';po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0];s.parentNode.insertBefore(po, s);
  })();

  $.getScript('http://platform.twitter.com/widgets.js', function(){
    twttr.events.bind('tweet', function(event) {
      if(event) {
        var targetUrl;
        if(event.target && event.target.nodeName == 'IFRAME') {
          targetUrl = extractParamFromUri(event.target.src, 'url');
        }
        _gaq.push(['_trackSocial', 'twitter', 'tweet', targetUrl]);
      }
    });
  });
}

function extractParamFromUri(uri, paramName) {
  if (!uri) {
    return;
  }
  var uri = uri.split('#')[0];
  var parts = uri.split('?');
  if (parts.length == 1) {
    return;
  }
  var query = decodeURI(parts[1]);

  // Find url param.
  paramName += '=';
  var params = query.split('&');
  for (var i = 0, param; param = params[i]; ++i) {
    if (param.indexOf(paramName) === 0) {
      return unescape(param.split('=')[1]);
    }
  }
}

function setupEntryPage() {
  $('#report-a-problem').click(function(e) {
    e.preventDefault();
    var reportBrokenLinkDialog = $('<div></div>')
    .load(
      $('#report-a-problem').attr('href'),
      function() {
        ajaxifyFormSubmit('#report-broken-link-form');
        $('#ReportBrokenLink_link', reportBrokenLinkDialog).val(document.location.href);
      }
    )
    .dialog( {
      autoOpen: false,
      modal: true,
      width:500,
      title: $('#report-a-problem').data('tip')
    });

    reportBrokenLinkDialog.dialog('open');
  });

  $('#vote-up').click(function(e) {
    e.preventDefault();
    voteAnEntry($(this).parent().data('entry'), +1, $(this));
  });

  $('#vote-down').click(function(e) {
    e.preventDefault();
    voteAnEntry($(this).parent().data('entry'), -1, $(this));
  });

  function voteAnEntry(entryId, value, voteCtrl) {
    $.post(
      voteCtrl.attr('href'),
      {
        'id':    entryId,
        'value': value
      },
      function(data) {
        if(data){
          voteCtrl.next().text(data);
        }
      }
    );
  }
}

function setupComments(hideCommentsForm) {
  if(hideCommentsForm) {
    $('#comments-form').hide();
    
    $('#comments-form-title').click(function() {
      $('#comments-form').show();
      return false;
    });
  }

  ajaxifyFormSubmit('#comments-form');

  $('.entry-comment').mouseenter(function() {
    $(this).addClass('hover');
  }).mouseleave(function() {
    $(this).removeClass('hover');
  });

  $('.comment-vote-up').click(function(e) {
    e.preventDefault();
    voteAComment($(this).parent().data('comment'), +1, $(this));
  });

  $('.comment-vote-down').click(function(e) {
    e.preventDefault();
    voteAComment($(this).parent().data('comment'), -1, $(this));
  });


  function voteAComment(commentId, value, votesCtrl) {
    $.post(
      votesCtrl.attr('href'),
      {
        'id':    commentId,
        'value': value
      },
      function(data) {
        if(data != '') {
          var commentVotesCtrl = $('.comment-votes', votesCtrl.parent().parent());
          commentVotesCtrl.text(data);
          commentVotesCtrl.removeClass('positive-votes negative-votes').addClass((data >= 0) ? 'positive-votes' : 'negative-votes');
        }
      }
    );
  }
}

function setupSearchForm() {
  applyPlaceholderAttribute($('#query'));
  applyPlaceholderAttribute($('#scholar-name'));

  $('#search-form').submit(function(e) {
    if($('#query').val() == '') {
      e.preventDefault();
    }
  });

  // Setup Advanced Search:
  $('#advanced-search-ctrl').click(function(e) {
    e.preventDefault();
    $('#search-wpr a').toggleClass('collapse');
    $('#advanced-search-wpr').slideToggle('slow');
  });

  $('#scholar-name').autocomplete({
    minLength: 2,
    source: function(request, response) {
      $.ajax({
        url: '/search/scholars-list',
        dataType: 'json',
        data: request
      }).done(function(data) {
        response(data);
      });
    },
    focus: function(event, ui) {
      $('#scholar-name').val(ui.item.label);
      return false;
    },
    select: function(event, ui) {
      $('#scholar-name').val(ui.item.label);
      return false;
    }
  });

  $('#search-form select[name^="category"]').focus(function() {
    var categoriesList = $(this);
    if($('option', categoriesList).length <= 1) {
      $('option:first-child', categoriesList).addClass('loading');
      $.get('/search/categories-list', function(data) {
        categoriesList.html(categoriesList.html() + data);
        $('option:first-child', categoriesList).removeClass('loading');
      });
    }
  });
}

function initHoverEffects() {
  $('#main-menu li > a').bind('mouseenter mouseleave', function() {
    $($(this).parent().prev().children()[0]).toggleClass('prev');
  });

  $('#footer-menu ul li a').bind('mouseenter mouseleave', function() {
    $($(this).parent().prev().children()[0]).toggleClass('prev');
  });

  $('#breadcrumbs li').bind('mouseenter mouseleave', function() {
    $(this).toggleClass('hover');
    $(this).prev().toggleClass('hover-prev');
  });

  $('ul.active-list li').mouseenter(function() {
    if($(this).attr('data-playlist')) {
      $(this).css('position', 'relative');
      $('#addto-playlist').css('top', 10).css(($('body').css('direction') == 'rtl') ? 'left' : 'right', 10).appendTo($(this));
    }
  }).mouseleave(function() {
    $(this).css('position', '');
    $('#addto-playlist').css('top', -10000);
  });
}

function setupTooltips() {
  $('a[data-tip]').hoverIntent( {
    sensitivity: 7,
    interval: 200,
    timeout: 0,
    over: function(){
      if($('#tooltip').length > 0) {
        $('#tooltip').remove();
      }

      var anchor = $(this);
      if($('#tooltip').length > 0) {
        $('#tooltip').remove();
      }
      var title = anchor.data('tip');
      var tipParts = title.replace(/\[([a-z0-9\-]+)\]/g, '<span class="ico" style="background-image:url(http://static.islamway.net/images/resources/$1-s.png);"></span>').split('|');
      var tip = $('<div id="tooltip"></div>').append('<div id="tooltip-content"></div>').append('<div id="tooltip-arrow"></div>');
      $('body').append(tip);
      var tipContent = $('#tooltip-content', tip);

      if(tipParts.length == 1) {
        tip.css('width', 'auto');
      } else {
        tip.css('width', '250');
        var tipTitle = tipParts.shift();
        tipContent.append('<h3>' + tipTitle + '</h3>');
      }

      var tpl = tipParts.length;
      for (var i = 0; i < tpl; i++) {
        tipContent.append('<p>' + tipParts[i] + '</p>');
      }
      $('#tooltip-arrow').css({top: tip.height() - 1, left: (tip.width() - 11) / 2});
      tip.position({my: "bottom", at: "top", of: anchor});
      tip.fadeIn(500);
    },
    out: function(){
      $('#tooltip').stop(true, true).hide();
    }
  });
}

function setupScholarsQuickInfo() {
  $('.scholar-link').mouseenter(function() {
    if($('.quick-info-positioner', $(this)).length == 0) {
      var link = $('a.scholar', $(this));
      var scholarId = link.data('id');
      link.before('<div class="quick-info-positioner"><div class="quick-info"><div class="quick-info-content"><div class="content-holder"><img src="http://static.islamway.net/images/progress-indicator.gif" /></div></div><div class="quick-info-arrow"></div></div></div>');
      $('.quick-info-positioner', $(this)).position({ my: "bottom", at: "top", of: link });
      $('.content-holder', $(this)).load('/scholar/' + scholarId + '/quick-info');
    }
    $('.quick-info-positioner', $(this)).show();
    var link = $('a.scholar', $(this));
    $('.quick-info-positioner', $(this)).position({ my: "bottom", at: "top", of: link });
  }).mouseleave(function() {
    $('.quick-info-positioner', $(this)).hide();
  });
}

function setupUserbar() {
  $('#userbar-handle').click(function() {
    $('.userbar-dialog').hide();
    var fullWidth = $('#userbar-wpr2').width() - 2;
    var collapsed = ($('#userbar').width() == 30);
    $('#userbar').css('overflow', collapsed ? 'visible' : 'hidden');
    $('#userbar').animate(
      {width: collapsed ? fullWidth : 30},
      'fast',
      function() {
        $('#userbar-handle').toggleClass('collapsed');
        $('#userbar-panels').toggle(collapsed);
        iwPortal.setPref('userbar', collapsed);
      }
    );
  });

  $('#theme-selector-ctrl').click(function(e) {
    e.preventDefault();
    $('.userbar-dialog:not(#theme-selector)').hide();
    $('#theme-selector').toggle();
  });

  $('#theme-selector ul.colors li').click(function() {
    var currentTheme = $('body').attr('class');
    var newTheme = $(this).attr('class').substr(6) + '-theme';
    $('body').removeClass(currentTheme).addClass(newTheme);
  });

  $('#apply-theme').click(function() {
    var currentTheme = $('body').attr('class');
    iwPortal.setPref('theme', currentTheme.substr(0, currentTheme.indexOf('-')));
    $('#theme-selector').hide();
  });

  $('#cancel-theme-preview').click(function() {
    var currentTheme = $('body').attr('class');
    var newTheme = iwPortal.getPref('theme', 'teal') + '-theme';
    $('body').removeClass(currentTheme).addClass(newTheme);
    $('#theme-selector').hide();
  });

  $('#widgets-catalog-ctrl').click(function(e) {
    e.preventDefault();
    $('.userbar-dialog:not(#widgets-catalog)').hide();
    $('#widgets-catalog').toggle();
  });

  $('#widgets-catalog input:checkbox').click(function() {
    var wdid = $(this).attr('id');
    if($(this).is(':checked')) {
      $.get('/widget/' + wdid, function(data) {
        var widget = $(data);
        $('#zone1').append(widget);
        iwPortal.addWidgetControls(widget);
        iwPortal.makeSortable();
      });
    } else {
      var widgets = iwPortal.getPref('widgets');
      for(n in widgets) {
        for(m in widgets[n]) {
          if(widgets[n][m].wdid == wdid) {
            $('.widget-zone:eq(' + n + ') .widget:eq(' + m + ') a.remove').click();
            break;
          }
        }
      }
    }
  });

  $('#apply-widgets').click(function() {
    $('#widgets-catalog').hide();
  });

  $('#add-feed').click(function(event) {
    event.preventDefault();
    var newFeedDialog = $('<div>URL: <input type="text" id="feed-url" style="width:300px; direction:ltr;" /></div>').dialog( {
      autoOpen: false,
      modal: true,
      width: 350,
      height:150,
      title: 'Add feed to your page',
      buttons:{
        Ok: function() {
          var url = $('#feed-url').val();
          var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
          if(regexp.test(url)) {
            iwPortal.addFeedReader(url, $('#zone1'));
          }
          $(this).dialog("close");
          $('#feed-url').remove();
        },
        Cancel: function() {
          $(this).dialog("close");
        }
      }
    });
    newFeedDialog.dialog('open');
  });

  Playlist.init();
}

$('.close-button').click(function(e) {
  e.preventDefault();
  var objectToHide = $(this).attr('href');
  if(objectToHide) {
    $(objectToHide).hide();
  } else {
    $(this).parent().hide();
  }
});

$('#online').click(function(e) {
  e.preventDefault();
  $.get($('#online').attr('href'), function(data) {
    var visitorsList = $('<div id="tooltip"></div>').append('<div id="tooltip-content" style="background:#2e3427;">' + data + '</div>');
    visitorsList.click(function() {$(this).remove();});
    $('body').append(visitorsList);
    visitorsList.position({my: 'bottom', at: 'top', of: '#online'});
    visitorsList.fadeIn(500);
  });
});


function loadFacebookLib() {
  window.fbAsyncInit = function() {
    FB.init({appId: '123429164410828', status: true, cookie: true, xfbml: true});
  };
  (function() {
    var e = document.createElement('script');e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
  }());
}

function setupEntryInfo() {
  $(document).on('mouseenter', '.entry-info', function() {
    $('.entry-info').removeClass('hover');
    $(this).addClass('hover');
    if($('.facebook-like', $(this)).html() == '') {
      $('.facebook-like', $(this)).html('<fb:like href="' + $('.facebook-like', $(this)).attr('data-href') + '" layout="button_count" show_faces="false" action="like" colorscheme="light"></fb:like>');
      $('.facebook-like', $(this)).each(function() {
        FB.XFBML.parse(this);
      });
    }
  }).on('mouseleave', '.entry-info', function() {
    $(this).removeClass('hover');
  });
}

function setupUserLocation(activateGeolocation) {
  $('.user-location').off('hover').mouseenter(function() {
    $('.user-location-ctrl', this).show();
  }).mouseleave(function() {
    $('.user-location-ctrl', this).hide();
  });

  $(document).off('click', '.user-location-ctrl').on('click', '.user-location-ctrl', function(event) {
    event.preventDefault();
    $(this).parent().addClass('loading');
    var url = $(this).parent().attr('action');
    $(this).parent().load(url, function() {
      $(this).removeClass('loading');
    });
  });

  $(document).off('change', '#country_list').on('change', '#country_list', function() {
    var form = $(this).parent();
    form.addClass('loading');
    var url = form.attr('action') + '?country=' + $('#country_list').val();
    $.get(url, function(data) {
      form.html(data);
      form.removeClass('loading');
      $('.user-location span').text($('#country_list option:selected').text() + '/' + $('#city_list option:selected').text());
      $(form).trigger('location.changed');
    });
  });

  $(document).off('change', '#city_list').on('change', '#city_list', function() {
    var form = $(this).parent();
    form.addClass('loading');
    var url = form.attr('action') + '?country=' + $('#country_list').val() + '&city=' + $('#city_list').val();
    $.get(url, function(data) {
      $('#city_list').parent().removeClass('loading');
      $('.user-location').html(data);
      $(form).trigger('location.changed');
    });
  });

  if (activateGeolocation && navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      $('.user-location').addClass('loading');
      var url = $('.user-location').attr('action') + '?latitude=' + position.coords.latitude + '&longitude=' + position.coords.longitude;
      $.get(url, function(data) {
        $('.user-location').html(data);
        $('.user-location').removeClass('loading');
        $('.user-location:first').trigger('location.changed');
      });
    });
  }
}

function ajaxifyFormSubmit(formId) {
  $(':submit', formId).click(function(event) {
    event.preventDefault();
    $.post(
      $(formId).attr('action'),
      $(formId).serialize(),
      function(data) {
        height = $(formId).parent().height();
        $(formId).parent().css('height', height);
        $(formId).parent().html(data);
        ajaxifyFormSubmit(formId);
      }
    );
  });
}

function initCategories() {
  $('.categories li > div').mouseenter(function() {
    $('.categories li > div').removeClass('hover');
    $(this).addClass('hover');
  }).mouseleave(function() {
    $(this).removeClass('hover');
  });

  if($('.categories ul.categories').length > 1) {
    $('.categories ul.categories').hide();
  }

  $('.categories li').click( function(event) {
    if(event.target.tagName == 'A') {
      return true;
    }
    if(!$(this).hasClass('subtree')) {
      return false;
    }
    event.stopPropagation();

    var subtree = $(this).children('ul.categories');
    if(subtree.is(':visible')) {
      subtree.slideUp('normal');
      $(this).removeClass('expanded');
    }

    if(!subtree.is(':visible')) {
      subtree.slideDown('normal');
      $(this).addClass('expanded');
    }
    return true;
  });
}

function setupViewers(viewers) {
  $('.viewer-ctrl').click( function(e) {
    e.preventDefault();
    $('embed', $('.viewer-wpr')).hide();
    $('.viewer-wpr').slideUp('slow');

    var wrapper = $(this).parent().parent().parent().parent().next();
    if(wrapper.hasClass('viewer-wpr')) {
      if(!wrapper.is(':visible')) {
        var resourceId = $('input[name=resourceId]', $(this).parent()).val();
        wrapper.slideDown('slow', function() {
          extraHeight = 0;
          if($('#userbar-wpr1').length) {
            extraHeight += $('#userbar-wpr1').height()
          }
          if($('.resource-wpr').index(wrapper.parent()) < ($('.resource-wpr').length - 1)) {
            extraHeight += wrapper.prev().height();
          }
          wrapper.scrollMinimal(true, extraHeight);
          if((typeof viewers['resource_' + resourceId].loaded == 'undefined') || (!viewers['resource_' + resourceId].loaded)) {
            $('.viewer', wrapper).html(viewers['resource_' + resourceId].html);
            viewers['resource_' + resourceId].loaded = true;
            var func = viewers['resource_' + resourceId].init;
            if($.isFunction(func)) func();
          }
          $('embed', wrapper).show();
        });
      } else {
        $('embed', wrapper).hide();
        wrapper.slideUp('slow');
      }
    }
  });
}

function setupEmbed() {
  $('.embed-code-wpr textarea').on('focus', function() {
    this.select();
  });

  $('.embed').click(function(e) {
    e.preventDefault();
    var embedWpr = $(this).next().clone(true);
    embedWpr.dialog( {
      autoOpen: false,
      modal: true,
      width:500,
      title: 'Embed',
      open: function(ev, ui) {setEmbedHtml($('input[name=embed-format]:checked')[0]);}
    }).dialog('open');
  });

  $('input[name=embed-format]').click(function() {
    setEmbedHtml($(this));
  });

  function setEmbedHtml(ctrl) {
    ctrl = $(ctrl);
    var resourceId = ctrl.attr('id').substr(9);
    var paramsPattern = /\?[^"]*/g;
    var widthPattern = /width=\"\d+\"/g;
    var heightPattern = /height=\"\d+\"/g;

    var params = ctrl.val();
    var embedHtml = ctrl.parent().parent().next().val()
      .replace(paramsPattern, '?' + params)
      .replace(widthPattern, 'width="' + viewers['resource_' + resourceId].width + '"')
      .replace(heightPattern, 'height="' + viewers['resource_' + resourceId].height + '"');
    ctrl.parent().parent().next().val(embedHtml);
  }
}

function setupNewsletterSubscriptionDialog() {
  $('#newsletter-subscription').click(function(e) {
    e.preventDefault();
    var sendToFriendDialog = $('<div></div>')
    .load(
      $('#newsletter-subscription').attr('href'),
      function() {
        ajaxifyFormSubmit('#newsletter-subscription-form');
      }
    )
    .dialog( {
      autoOpen: false,
      modal: true,
      width:500,
      title: $('#newsletter-subscription').data('tip')
    });

    var left = ($(window).width() - 500) / 2;
    sendToFriendDialog.dialog('option', 'position', [left, 70]).dialog('open');
  });
}

function setupMembershipDialogs() {
  $('#signup, #signin').click(function(e) {
    var id = $(this).attr('id');
    e.preventDefault();
    var dlg = $('<div id="' + id + '-dlg"></div>')
    .load(
      $('#' + id).attr('href'),
      function() {
        ajaxifyFormSubmit('#' + (id == 'signup' ? 'sf_apply_apply_form' : 'signin-form'));
        setupFacebookSignin();
      }
    )
    .dialog( {
      autoOpen: false,
      modal: true,
      width:500,
      title: $('#' + id).text()
    });

    var left = ($(window).width() - 500) / 2;
    dlg.dialog('option', 'position', [left, 70]).dialog('open');
  });
}

function setupFacebookSignin() {
  window.fbAsyncInit = function() {
    FB.init({
      appId  : '100122710133231',
      oauth  : true,
      status : true,
      cookie : true,
      xfbml  : true
    });
  };
  
  (function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
  }());
  
  $('.facebook-login').click(function(e) {
    e.preventDefault();
    FB.login(function(response) {
      if (response.authResponse) {
        $('#signin-dlg').dialog('close');
        location.reload();
      } else {
        //user hit cancel button
      }
    },
    { scope: 'publish_stream,email' });
  });
}

function setupUnlimitedScroll() {
  $(document).on('click', '#load-more', function(e) {
    e.preventDefault();
    loadMoreEntries();
  });

  $(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() - $(document).height() >= -2) {
      loadMoreEntries();
    }
  });

  function loadMoreEntries() {
    if($('#load-more').length > 0) {
      var url = $('#load-more').attr('href');
      $('#pager-wpr').css('padding', 2);
      $('#pager-wpr').html('<img src="http://static.islamway.net/images/progress-indicator.gif" alt="Loading ..." />');
      $.get(url, function(data) {
        $('#pager-wpr').replaceWith($(data));
        if (typeof _gaq !== "undefined" && _gaq !== null) {
          _gaq.push(['_trackPageview', url]);
        }
      });
    }
  }
}

function setupTestimonialsDialog() {
  $('#addTestimonial').on('click', function(event) {
    event.preventDefault();
    var testimonialsDialog = $('<div></div>').load(
      $('#addTestimonial').attr('href'),
      function() {
        ajaxifyFormSubmit('#testimonialForm');
      }
    ).dialog( {
      autoOpen: false,
      modal: true,
      position:['center', 120],
      width:500,
      title: $('#addTestimonial IMG').attr('title')
    });
    testimonialsDialog.dialog('open');
  });
}

/******************************************************************************/
// Utils:

// jCarouselLite - jQuery plugin to navigate any content in a carousel style widget [http://gmarwaha.com/jquery/jcarousellite/]
(function($) {
  $.fn.jCarouselLite = function(o) {
    o = $.extend( {
      btnPrev: null,
      btnNext: null,
      btnGo: null,
      mouseWheel: false,
      auto: null,
      hoverPause: false,

      speed: 200,
      easing: null,

      vertical: false,
      circular: true,
      visible: 3,
      start: 0,
      scroll: 1,

      beforeStart: null,
      afterEnd: null
    }, o || {});

    return this.each( function() {
      var running = false, animCss = o.vertical ? 'top' : 'left', sizeCss = o.vertical ? 'height' : 'width';
      var div = $(this), ul = $('ul', div), tLi = $('li', ul), tl = tLi.size(), v = o.visible;

      if(o.circular) {
        ul.prepend(tLi.slice(tl-v+1).clone()).append(tLi.slice(0,o.scroll).clone());
        o.start += v-1;
      }

      var li = $('li', ul), itemLength = li.size(), curr = o.start;
      div.css('visibility', 'visible');

      li.css({overflow: 'hidden', 'float': o.vertical ? 'none' : 'left'});
      ul.css({margin: '0', padding: '0', position: 'relative', 'list-style-type': 'none', 'z-index': '1'});
      div.css({overflow: 'hidden', position: 'relative', 'z-index': '2', left: '0px'});

      var liSize = o.vertical ? height(li) : width(li);
      var ulSize = liSize * itemLength;
      var divSize = liSize * v;

      li.css({width: li.width(), height: li.height()});
      ul.css(sizeCss, ulSize+'px').css(animCss, -(curr*liSize));

      div.css(sizeCss, divSize+'px');

      if(o.btnPrev) {
        $(o.btnPrev).click(function() {
          return go(curr-o.scroll);
        });
        if(o.hoverPause) {
          $(o.btnPrev).mouseenter(function(){ stopAuto(); }).mouseleave(function(){ startAuto(); });
        }
      }

      if(o.btnNext) {
        $(o.btnNext).click(function() {
          return go(curr+o.scroll);
        });
        if(o.hoverPause) {
          $(o.btnNext).mouseenter(function(){ stopAuto(); }).mouseleave(function(){ startAuto(); });
        }
      }

      if(o.btnGo)
        $.each(o.btnGo, function(i, val) {
          $(val).click(function() {
            return go(o.circular ? o.visible+i : i);
          });
        });

      if(o.mouseWheel && div.mousewheel)
        div.mousewheel(function(e, d) {
          return d>0 ? go(curr-o.scroll) : go(curr+o.scroll);
        });

      var autoInterval;

      function startAuto() {
        stopAuto();
        autoInterval = setInterval(function() {
          go(curr+o.scroll);
        }, o.auto+o.speed);
      };

      function stopAuto() {
        clearInterval(autoInterval);
      };

      if(o.auto) {
        if(o.hoverPause) {
          div.mouseenter(function(){ stopAuto(); }).mouseleave(function(){ startAuto(); });
        }
        startAuto();
      };

      function vis() {
        return li.slice(curr).slice(0,v);
      };

      function go(to) {
        if(!running) {
          if(o.beforeStart)
            o.beforeStart.call(this, vis());

          if(o.circular) {
            if(to < 0) {
              ul.css(animCss, -( (curr + tl) * liSize) + 'px');
              curr = to + tl;
            } else if(to>itemLength-v) {
              ul.css(animCss, -( (curr - tl) * liSize ) + 'px' );
              curr = to - tl;
            } else curr = to;
          } else {
            if(to <0 || to > itemLength - v) return;
            else curr = to;
          }

          running = true;
          ul.animate(
            animCss == 'left' ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
            function() {
            if(o.afterEnd)
              o.afterEnd.call(this, vis());
              running = false;
            }
          );

          if(!o.circular) {
            $(o.btnPrev + ',' + o.btnNext).removeClass('disabled');
            $( (curr-o.scroll<0 && o.btnPrev)
              ||
            (curr+o.scroll > itemLength-v && o.btnNext)
              ||
            []
            ).addClass('disabled');
          }
        }
        return false;
      };
    });
  };

  function css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
  };
  function width(el) {
    return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
  };
  function height(el) {
    return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
  };

})(jQuery);

// Scroll so that an element is visible:
jQuery.fn.scrollMinimal = function(smooth, extraHeight) {
  var cTop = this.offset().top;
  var cHeight = this.outerHeight(true) + extraHeight;
  var windowTop = $(window).scrollTop();
  var visibleHeight = $(window).height();

  if (cTop < windowTop) {
    if (smooth) {
      $('body').animate({'scrollTop': cTop}, 'slow', 'swing');
    } else {
      $(window).scrollTop(cTop);
    }
  } else if (cTop + cHeight > windowTop + visibleHeight) {
    if (smooth) {
      $('body').animate({'scrollTop': cTop - visibleHeight + cHeight}, 'slow', 'swing');
    } else {
      $(window).scrollTop(cTop - visibleHeight + cHeight);
    }
  }
};

// Hover event with delay
(function($) {
	$.fn.hoverIntent = function(f,g) {
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		var cX, cY, pX, pY;
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				pX = cX; pY = cY;
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		var handleHover = function(e) {
			var ev = jQuery.extend({},e);
			var ob = this;
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			if (e.type == "mouseenter") {
				pX = ev.pageX; pY = ev.pageY;
				$(ob).bind("mousemove",track);
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
			} else {
				$(ob).unbind("mousemove",track);
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
	};
})(jQuery);

// Apply placeholder attribute behavior in web browsers that don't support it:
function applyPlaceholderAttribute(field) {
  var clearValue = function () {
    if (field.val() === originalText) {
      field.val('');
    }
  };

  if (!('placeholder' in document.createElement('input'))) {
    var originalText = field.attr('placeholder');

    if (!field.val().length) {
      field.val(originalText);
      field.addClass('placeholder');
    }

    field.on('focus', function () {
      field.removeClass('placeholder');
      clearValue();
    });

    field.on('blur', function () {
      if (!field.val().length) {
        field.val(originalText);
        field.addClass('placeholder');
      }
    });

    // Empty the placeholder text at form submit if it hasn't changed
    field.parents('form').on('submit', function () {
      clearValue();
    });
    // Clear at window reload to avoid it stored in autocomplete
    $(window).on('unload', function () {
      clearValue();
    });
  }
}